﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 入库表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class StorageService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Storage> _storageRep;
    private readonly SysFileService _sysFileService;
    private readonly ISqlSugarClient _sqlSugarClient;

    public StorageService(SqlSugarRepository<Storage> storageRep, SysFileService sysFileService, ISqlSugarClient sqlSugarClient)
    {
        _storageRep = storageRep;
        _sysFileService = sysFileService;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询入库表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询入库表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<StorageOutput>> Page(PageStorageInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _storageRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.StorageCode.Contains(input.Keyword) || u.StorageIdType.Contains(input.Keyword) || u.StorageStatus.Contains(input.Keyword) || u.Contact.Contains(input.Keyword) || u.ContactNumber.Contains(input.Keyword) || u.StorageDesc.Contains(input.Keyword) || u.UploadAttachments.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.StorageCode), u => u.StorageCode.Contains(input.StorageCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.StorageIdType), u => u.StorageIdType.Contains(input.StorageIdType.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.StorageStatus), u => u.StorageStatus.Contains(input.StorageStatus.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Contact), u => u.Contact.Contains(input.Contact.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ContactNumber), u => u.ContactNumber.Contains(input.ContactNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.StorageDesc), u => u.StorageDesc.Contains(input.StorageDesc.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.UploadAttachments), u => u.UploadAttachments.Contains(input.UploadAttachments.Trim()))
            .WhereIF(input.InboundId != null, u => u.InboundId == input.InboundId)
            .WhereIF(input.StorageDateRange?.Length == 2, u => u.StorageDate >= input.StorageDateRange[0] && u.StorageDate <= input.StorageDateRange[1])
            .WhereIF(input.IncomingOrdersId != null, u => u.IncomingOrdersId == input.IncomingOrdersId)
            .WhereIF(input.StorageNumber != null, u => u.StorageNumber == input.StorageNumber)
            .WhereIF(input.StorageMoney != null, u => u.StorageMoney == input.StorageMoney)
            .WhereIF(input.Vendor != null, u => u.Vendor == input.Vendor)
            .WhereIF(input.OrganizationalStructureId != null, u => u.OrganizationalStructureId == input.OrganizationalStructureId)
            .WhereIF(input.Attn != null, u => u.Attn == input.Attn)
            .WhereIF(input.FormsPerson != null, u => u.FormsPerson == input.FormsPerson)
            .WhereIF(input.FormsTimeRange?.Length == 2, u => u.FormsTime >= input.FormsTimeRange[0] && u.FormsTime <= input.FormsTimeRange[1])
            .WhereIF(input.Department != null, u => u.Department == input.Department)
            .WhereIF(input.Reviewers != null, u => u.Reviewers == input.Reviewers)
            .WhereIF(input.ReviewTimeRange?.Length == 2, u => u.ReviewTime >= input.ReviewTimeRange[0] && u.ReviewTime <= input.ReviewTimeRange[1])
            .LeftJoin<WarehouseInfo>((u, inbound) => u.InboundId == inbound.Id)
            .LeftJoin<Incomingorders>((u, inbound, incomingOrders) => u.IncomingOrdersId == incomingOrders.Id)
            .LeftJoin<Vendor>((u, inbound, incomingOrders, vendor) => u.Vendor == vendor.Id)
            .LeftJoin<department>((u, inbound, incomingOrders, vendor, organizationalStructure) => u.OrganizationalStructureId == organizationalStructure.Id)
            .LeftJoin<UserInfo>((u, inbound, incomingOrders, vendor, organizationalStructure, attn) => u.Attn == attn.Id)
            .LeftJoin<UserInfo>((u, inbound, incomingOrders, vendor, organizationalStructure, attn, formsPerson) => u.FormsPerson == formsPerson.Id)
            .LeftJoin<department>((u, inbound, incomingOrders, vendor, organizationalStructure, attn, formsPerson, department) => u.Department == department.Id)
            .LeftJoin<UserInfo>((u, inbound, incomingOrders, vendor, organizationalStructure, attn, formsPerson, department, reviewers) => u.Reviewers == reviewers.Id)
            .Select((u, inbound, incomingOrders, vendor, organizationalStructure, attn, formsPerson, department, reviewers) => new StorageOutput
            {
                Id = u.Id,
                StorageCode = u.StorageCode,
                StorageIdType = u.StorageIdType,
                StorageStatus = u.StorageStatus,
                InboundId = u.InboundId,
                InboundFkDisplayName = $"{inbound.WarehouseName}",
                StorageDate = u.StorageDate,
                IncomingOrdersId = u.IncomingOrdersId,
                IncomingOrdersFkDisplayName = $"{incomingOrders.IncomingNumber}",
                StorageNumber = u.StorageNumber,
                StorageMoney = u.StorageMoney,
                Vendor = u.Vendor,
                VendorFkDisplayName = $"{vendor.VendorName}",
                Contact = u.Contact,
                ContactNumber = u.ContactNumber,
                OrganizationalStructureId = u.OrganizationalStructureId,
                OrganizationalStructureFkDisplayName = $"{organizationalStructure.DepartmentName}",
                Attn = u.Attn,
                AttnFkDisplayName = $"{attn.UserName}",
                StorageDesc = u.StorageDesc,
                UploadAttachments = u.UploadAttachments,
                FormsPerson = u.FormsPerson,
                FormsPersonFkDisplayName = $"{formsPerson.UserName}",
                FormsTime = u.FormsTime,
                Department = u.Department,
                DepartmentFkDisplayName = $"{department.DepartmentName}",
                Reviewers = u.Reviewers,
                ReviewersFkDisplayName = $"{reviewers.UserName}",
                ReviewTime = u.ReviewTime,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取入库表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取入库表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Storage> Detail([FromQuery] QueryByIdStorageInput input)
    {
        return await _storageRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加入库表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加入库表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddStorageInput input)
    {
        var entity = input.Adapt<Storage>();
        return await _storageRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新入库表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新入库表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateStorageInput input)
    {
        var entity = input.Adapt<Storage>();
        await _storageRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除入库表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除入库表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteStorageInput input)
    {
        var entity = await _storageRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _storageRep.FakeDeleteAsync(entity);   //假删除
        //await _storageRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除入库表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除入库表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteStorageInput> input)
    {
        var exp = Expressionable.Create<Storage>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _storageRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _storageRep.FakeDeleteAsync(list);   //假删除
        //return await _storageRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 上传上传附件 ⬆️
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [DisplayName("上传上传附件")]
    [ApiDescriptionSettings(Name = "UploadUploadAttachments"), HttpPost]
    public async Task<SysFile> UploadUploadAttachments([Required] IFormFile file)
    {
        return await _sysFileService.UploadFile(new UploadFileInput { File = file, SavePath = "upload/Storage/UploadAttachments" }); 
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataStorageInput input)
    {
        var inboundIdData = await _storageRep.Context.Queryable<WarehouseInfo>()
            .InnerJoinIF<Storage>(input.FromPage, (u, r) => u.Id == r.InboundId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.WarehouseName}"
            }).ToListAsync();
        var incomingOrdersIdData = await _storageRep.Context.Queryable<Incomingorders>()
            .InnerJoinIF<Storage>(input.FromPage, (u, r) => u.Id == r.IncomingOrdersId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.IncomingNumber}"
            }).ToListAsync();
        var vendorData = await _storageRep.Context.Queryable<Vendor>()
            .InnerJoinIF<Storage>(input.FromPage, (u, r) => u.Id == r.Vendor)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.VendorName}"
            }).ToListAsync();
        var organizationalStructureIdData = await _storageRep.Context.Queryable<department>()
            .InnerJoinIF<Storage>(input.FromPage, (u, r) => u.Id == r.OrganizationalStructureId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.DepartmentName}"
            }).ToListAsync();
        var attnData = await _storageRep.Context.Queryable<UserInfo>()
            .InnerJoinIF<Storage>(input.FromPage, (u, r) => u.Id == r.Attn)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        var formsPersonData = await _storageRep.Context.Queryable<UserInfo>()
            .InnerJoinIF<Storage>(input.FromPage, (u, r) => u.Id == r.FormsPerson)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        var departmentData = await _storageRep.Context.Queryable<department>()
            .InnerJoinIF<Storage>(input.FromPage, (u, r) => u.Id == r.Department)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.DepartmentName}"
            }).ToListAsync();
        var reviewersData = await _storageRep.Context.Queryable<UserInfo>()
            .InnerJoinIF<Storage>(input.FromPage, (u, r) => u.Id == r.Reviewers)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "inboundId", inboundIdData },
            { "incomingOrdersId", incomingOrdersIdData },
            { "vendor", vendorData },
            { "organizationalStructureId", organizationalStructureIdData },
            { "attn", attnData },
            { "formsPerson", formsPersonData },
            { "department", departmentData },
            { "reviewers", reviewersData },
        };
    }
    
    /// <summary>
    /// 导出入库表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出入库表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageStorageInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportStorageOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "入库表导出记录");
    }
    
    /// <summary>
    /// 下载入库表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载入库表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportStorageOutput>(), "入库表导入模板", (_, info) =>
        {
            if (nameof(ExportStorageOutput.InboundFkDisplayName) == info.Name) return _storageRep.Context.Queryable<WarehouseInfo>().Select(u => $"{u.WarehouseName}").Distinct().ToList();
            if (nameof(ExportStorageOutput.IncomingOrdersFkDisplayName) == info.Name) return _storageRep.Context.Queryable<Incomingorders>().Select(u => $"{u.IncomingNumber}").Distinct().ToList();
            if (nameof(ExportStorageOutput.VendorFkDisplayName) == info.Name) return _storageRep.Context.Queryable<Vendor>().Select(u => $"{u.VendorName}").Distinct().ToList();
            if (nameof(ExportStorageOutput.OrganizationalStructureFkDisplayName) == info.Name) return _storageRep.Context.Queryable<department>().Select(u => $"{u.DepartmentName}").Distinct().ToList();
            if (nameof(ExportStorageOutput.AttnFkDisplayName) == info.Name) return _storageRep.Context.Queryable<UserInfo>().Select(u => $"{u.UserName}").Distinct().ToList();
            if (nameof(ExportStorageOutput.FormsPersonFkDisplayName) == info.Name) return _storageRep.Context.Queryable<UserInfo>().Select(u => $"{u.UserName}").Distinct().ToList();
            if (nameof(ExportStorageOutput.DepartmentFkDisplayName) == info.Name) return _storageRep.Context.Queryable<department>().Select(u => $"{u.DepartmentName}").Distinct().ToList();
            if (nameof(ExportStorageOutput.ReviewersFkDisplayName) == info.Name) return _storageRep.Context.Queryable<UserInfo>().Select(u => $"{u.UserName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入入库表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入入库表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportStorageInput, Storage>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 仓库名称
                    var inboundIdLabelList = pageItems.Where(x => x.InboundFkDisplayName != null).Select(x => x.InboundFkDisplayName).Distinct().ToList();
                    if (inboundIdLabelList.Any()) {
                        var inboundIdLinkMap = _storageRep.Context.Queryable<WarehouseInfo>().Where(u => inboundIdLabelList.Contains($"{u.WarehouseName}")).ToList().ToDictionary(u => $"{u.WarehouseName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.InboundId = inboundIdLinkMap.GetValueOrDefault(e.InboundFkDisplayName ?? "");
                            if (e.InboundId == null) e.Error = "仓库名称链接失败";
                        });
                    }
                    // 链接 进货订单编号
                    var incomingOrdersIdLabelList = pageItems.Where(x => x.IncomingOrdersFkDisplayName != null).Select(x => x.IncomingOrdersFkDisplayName).Distinct().ToList();
                    if (incomingOrdersIdLabelList.Any()) {
                        var incomingOrdersIdLinkMap = _storageRep.Context.Queryable<Incomingorders>().Where(u => incomingOrdersIdLabelList.Contains($"{u.IncomingNumber}")).ToList().ToDictionary(u => $"{u.IncomingNumber}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.IncomingOrdersId = incomingOrdersIdLinkMap.GetValueOrDefault(e.IncomingOrdersFkDisplayName ?? "");
                            if (e.IncomingOrdersId == null) e.Error = "进货订单编号链接失败";
                        });
                    }
                    // 链接 供应商
                    var vendorLabelList = pageItems.Where(x => x.VendorFkDisplayName != null).Select(x => x.VendorFkDisplayName).Distinct().ToList();
                    if (vendorLabelList.Any()) {
                        var vendorLinkMap = _storageRep.Context.Queryable<Vendor>().Where(u => vendorLabelList.Contains($"{u.VendorName}")).ToList().ToDictionary(u => $"{u.VendorName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Vendor = vendorLinkMap.GetValueOrDefault(e.VendorFkDisplayName ?? "");
                            if (e.Vendor == null) e.Error = "供应商链接失败";
                        });
                    }
                    // 链接 组织机构
                    var organizationalStructureIdLabelList = pageItems.Where(x => x.OrganizationalStructureFkDisplayName != null).Select(x => x.OrganizationalStructureFkDisplayName).Distinct().ToList();
                    if (organizationalStructureIdLabelList.Any()) {
                        var organizationalStructureIdLinkMap = _storageRep.Context.Queryable<department>().Where(u => organizationalStructureIdLabelList.Contains($"{u.DepartmentName}")).ToList().ToDictionary(u => $"{u.DepartmentName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.OrganizationalStructureId = organizationalStructureIdLinkMap.GetValueOrDefault(e.OrganizationalStructureFkDisplayName ?? "");
                            if (e.OrganizationalStructureId == null) e.Error = "组织机构链接失败";
                        });
                    }
                    // 链接 经办人
                    var attnLabelList = pageItems.Where(x => x.AttnFkDisplayName != null).Select(x => x.AttnFkDisplayName).Distinct().ToList();
                    if (attnLabelList.Any()) {
                        var attnLinkMap = _storageRep.Context.Queryable<UserInfo>().Where(u => attnLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Attn = attnLinkMap.GetValueOrDefault(e.AttnFkDisplayName ?? "");
                            if (e.Attn == null) e.Error = "经办人链接失败";
                        });
                    }
                    // 链接 制单人
                    var formsPersonLabelList = pageItems.Where(x => x.FormsPersonFkDisplayName != null).Select(x => x.FormsPersonFkDisplayName).Distinct().ToList();
                    if (formsPersonLabelList.Any()) {
                        var formsPersonLinkMap = _storageRep.Context.Queryable<UserInfo>().Where(u => formsPersonLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.FormsPerson = formsPersonLinkMap.GetValueOrDefault(e.FormsPersonFkDisplayName ?? "");
                            if (e.FormsPerson == null) e.Error = "制单人链接失败";
                        });
                    }
                    // 链接 所在部门
                    var departmentLabelList = pageItems.Where(x => x.DepartmentFkDisplayName != null).Select(x => x.DepartmentFkDisplayName).Distinct().ToList();
                    if (departmentLabelList.Any()) {
                        var departmentLinkMap = _storageRep.Context.Queryable<department>().Where(u => departmentLabelList.Contains($"{u.DepartmentName}")).ToList().ToDictionary(u => $"{u.DepartmentName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Department = departmentLinkMap.GetValueOrDefault(e.DepartmentFkDisplayName ?? "");
                            if (e.Department == null) e.Error = "所在部门链接失败";
                        });
                    }
                    // 链接 审核人
                    var reviewersLabelList = pageItems.Where(x => x.ReviewersFkDisplayName != null).Select(x => x.ReviewersFkDisplayName).Distinct().ToList();
                    if (reviewersLabelList.Any()) {
                        var reviewersLinkMap = _storageRep.Context.Queryable<UserInfo>().Where(u => reviewersLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Reviewers = reviewersLinkMap.GetValueOrDefault(e.ReviewersFkDisplayName ?? "");
                            if (e.Reviewers == null) e.Error = "审核人链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Storage>>();
                    
                    var storageable = _storageRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.StorageCode?.Length > 32, "入库单号长度不能超过32个字符")
                        .SplitError(it => it.Item.StorageIdType?.Length > 32, "入库类型长度不能超过32个字符")
                        .SplitError(it => it.Item.StorageStatus?.Length > 32, "入库状态长度不能超过32个字符")
                        .SplitError(it => it.Item.Contact?.Length > 32, "联系人长度不能超过32个字符")
                        .SplitError(it => it.Item.ContactNumber?.Length > 32, "联系方式长度不能超过32个字符")
                        .SplitError(it => it.Item.StorageDesc?.Length > 32, "备注长度不能超过32个字符")
                        .SplitError(it => it.Item.UploadAttachments?.Length > 32, "上传附件长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
